package com.isolation.harassed.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.text.TextUtils;

/**
 * MD5加密工具类，仅支持输出16或32位小写字母的MD5编码
 * 
 * @author allon
 * @version 1.0.1
 * @date 2016年6月15日
 */
public class MD5Encode {
	private static final String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	public static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; ++i)
			resultSb.append(byteToHexString(b[i]));

		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	/**
	 * 将输入字符串转换为16位长度的MD5值
	 * 
	 * @param origin
	 *            转换前的字符号
	 * @return 转换后的MD5值
	 */
	public static String from(String origin) {
		return from(origin, true);
	}

	public static String from(String origin, boolean _16) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			return origin;
		}
		if (!TextUtils.isEmpty(origin) && md != null) {
			byte[] input = origin.getBytes();
			String out = byteArrayToHexString(md.digest(input));
			if (_16 && out.length() >= 24) {
				out = out.substring(8, 24);
			}
			return out;
		}
		return origin;
	}
}